from sys import exc_info
from muMod import *
from win32.win32gui import FindWindow, SetWindowPos
wins = []

title = "永恒之巅"
#hwnd = FindWindow(None, title)
hwnd = 263734
SetWindowPos(hwnd, -1, 736, 332, 864, 530, 1) #窗口下沉
sleep(1)
rect = RECT()
if hwnd:
	windll.user32.GetWindowRect(hwnd, byref(rect))

window={"hWnd":hwnd, "rect":rect, "map":"godu", "mode":"hold", "line":1, "coords":[]}
little_img = cv2.imread('./Pics/MU_little.png')	 # 小怪挂机标记

def hold_Play(window, monitor = 0, top = False):
	#print(window["title"], window["map"])
#	try:
	n = 0
	while True:
		rect = window["rect"]
		hWnd = window["hWnd"]
		diagClose(hWnd, rect, monitor, window["map"], window["line"], top) # 检测界面异常
		image = loc_capture(hWnd, rect, monitor, top)
		little_result = find_template(image[367:383, 500:516], little_img)
		if little_result is None or little_result["confidence"]<0.7 or len(window["coords"]) == 0 or n == 20:
			map_result = None
			while map_result is None or map_result["confidence"]<0.7:
				close_all(rect, monitor, hWnd)
				bkg_click(hWnd, (770,110)) # 打开地图
				sleep(0.2)
				bkg_click(hWnd, (760,340)); sleep(0.5)  # 放大
				image = loc_capture(hWnd, rect, monitor, top)
				map_result = find_template(image[90:107, 146:180], map_img)
			sleep(2.5)
			player_des = getPlayer(image)
			if not player_des: # 定位玩家位置失败
				bkg_click(hWnd, window["coords"][0])
			elif len(window["coords"]) == 0:
				window["coords"] = [player_des["result"]]
				print(window["coords"])
			elif np.linalg.norm(np.array(player_des["result"]) - np.array(window["coords"][0]), ord=1) > 20:
				bkg_click(hWnd, window["coords"][0])
			bkg_click(hWnd, (102,97)) # 关闭地图
			sleep(10)
		else:	#降低回收操作频率
			n = n+1 if n<20 else 0
			if n == 20:
				# 回收
				bkg_click(hWnd, coords_spec["pack"]); sleep(3)
				bkg_click(hWnd, (815,485)); sleep(2) # 整理
				bkg_click(hWnd, coords_spec["recycle1"]); sleep(3)
				bkg_click(hWnd, coords_spec["recycle2"]); sleep(3)
				#close_all(rect, monitor, hWnd)
				bkg_click(hWnd, (609,62))
				#sleep(tsleep)
		act_stat = handAct(hWnd, rect,  monitor, top)
		if not act_stat[1]:
			bkg_click(hWnd, coords_spec["hand"])  # 点击手动
		sleep(20)
#	except:
#		print("Unexpected error:", exc_info()[0:2])
#		pass

hold_Play(window, 0, False)
	